#!/usr/bin/python
#coding=utf-8

import os
import requests
import time
import re
from datetime import datetime

# configuration for pgyer
USER_KEY = "b15b68xxxxxxxxxxxxxx95642bf45fa82"
API_KEY = "1e170462xxxxxxxxxxxxxx45299f5f8af"
PGYER_UPLOAD_URL = "https://www.pgyer.com/apiv1/app/upload"


def parseUploadResult(jsonResult):
    print 'post response: %s' % jsonResult
    resultCode = jsonResult['code']

    if resultCode != 0:
        print "Upload Fail!"
        raise Exception("Reason: %s" % jsonResult['message'])

    print "Upload Success"
    appKey = jsonResult['data']['appKey']
    appQRCodeURL = jsonResult['data']['appQRCodeURL']
    appDownloadPageURL = "https://www.pgyer.com/%s" % appKey
    print "appDownloadPage: %s, appQRCodeURL: %s" % (appDownloadPageURL,appQRCodeURL)
    #print "appQRCodeURL: %s" % appQRCodeURL
    return appDownloadPageURL, appQRCodeURL

def uploadAppToPgyer(appPath, updateDescription):
    print "Begin to upload ipa to Pgyer: %s" % appPath
    headers = {'enctype': 'multipart/form-data'}
    payload = {
        'uKey': USER_KEY,
        '_api_key': API_KEY,
        'publishRange': '2', # 直接发布
        'isPublishToPublic': '2', # 不发布到广场
        'updateDescription': updateDescription  # 版本更新描述
    }

    try_times = 0
    while try_times < 5:
        try:
            print "uploading ... %s" % datetime.now()
            app_file = {'file': open(appPath, 'rb')}
            r = requests.post(PGYER_UPLOAD_URL,
                headers = headers,
                files = app_file,
                data = payload
            )
            assert r.status_code == requests.codes.ok
            result = r.json()
            appDownloadPageURL, appQRCodeURL = parseUploadResult(result)
            return appDownloadPageURL, appQRCodeURL
        except requests.exceptions.ConnectionError:
            print "requests.exceptions.ConnectionError occured!"
            time.sleep(60)
            print "try again ... %s" % datetime.now()
            try_times += 1
        except Exception as e:
            print "Exception occured: %s" % str(e)
            time.sleep(60)
            print "try again ... %s" % datetime.now()
            try_times += 1

        if try_times >= 5:
            raise Exception("Failed to upload ipa to Pgyer, retried 5 times.")


if __name__ == "__main__":
    uploadAppToPgyer('build/outputs/apk/android-ci-release.apk', '修改少量bug')
